package com.finger.gulimall.order.service.impl;

import java.math.BigDecimal;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.finger.common.utils.PageUtils;
import com.finger.common.utils.Query;
import com.finger.gulimall.order.dao.PaymentInfoDao;
import com.finger.gulimall.order.entity.PaymentInfoEntity;
import com.finger.gulimall.order.entity.vo.PayAsyncVo;
import com.finger.gulimall.order.enume.OrderStatusEnum;
import com.finger.gulimall.order.service.OrderService;
import com.finger.gulimall.order.service.PaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service("paymentInfoService")
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoDao, PaymentInfoEntity> implements PaymentInfoService {

    @Autowired
    OrderService orderService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PaymentInfoEntity> page = this.page(
                new Query<PaymentInfoEntity>().getPage(params),
                new QueryWrapper<PaymentInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public String payedNotify(PayAsyncVo payAsyncVo) {

        if ("TRADE_SUCCESS".equals(payAsyncVo.getTrade_status())) {
            PaymentInfoEntity infoEntity = new PaymentInfoEntity();
            infoEntity.setAlipayTradeNo(payAsyncVo.getTrade_no());
            infoEntity.setCallbackTime(payAsyncVo.getNotify_time());
            infoEntity.setPaymentStatus(OrderStatusEnum.PAYED.getMsg());
            infoEntity.setCallbackContent(JSON.toJSONString(payAsyncVo));
            infoEntity.setOrderSn(payAsyncVo.getOut_trade_no());
            infoEntity.setTotalAmount(new BigDecimal(payAsyncVo.getTotal_amount()));

            this.baseMapper.insert(infoEntity);
            orderService.updateOrderStatus(infoEntity.getOrderSn(),OrderStatusEnum.PAYED.getCode());
        }

        return null;
    }
}